
<template>
    <div />
</template>
  
<script>
import { TreeSelect } from 'ant-design-vue'
// EdgeTabManager全局函数已通过统一的TabManager注册，无需额外导入
export default {
    name: 'JsonSchemaPushSetting',
    components: {},
    data() {
        return {
            form: this.$form.createForm(this, { name: 'coordinated' }),
            pushType: 'pushTypePeriod',
            pushStrategy: false,
            pushPeriodValue: 10,
            pushPeriodUnit: 'pushPeriodSecond',
            publishTopic: undefined,
            subscribeTopic: undefined,
            selPublishTopicArray: new Array(),
            selSubscribeTopicArray: new Array(),
            selTopicArray: new Array(),
            configName: '',
            SHOW_PARENT: TreeSelect.SHOW_PARENT,
            treeData: undefined,
            treeDataPub: undefined,
            treeDataSub: undefined
        }
    },
    mounted() {
        document.addEventListener('vue_event', ev => {
            let para = ev.detail.para
            switch (para) {
                case 'save':
                    this.saveJsonFile()
                    break
                case 'get':
                    this.getConfig()
                    break
                case 'focus':
                    // this.$refs.configNameRef.focus();
                    break          
                default:
                    break
            }
        })
    },
    methods: {
        async saveConfig() {
            if (this.configName === '') {
                this.$message.error('请填写配置名称')
                return false
            }
            const jsonObject = {
                pushType: this.pushType,
                pushStrategy: this.pushStrategy,
                pushPeriodValue: this.pushPeriodValue,
                pushPeriodUnit: this.pushPeriodUnit,
                publishTopic: this.publishTopic,
                subscribeTopic: this.subscribeTopic,
                configName: this.configName
            }
            const jsonData = JSON.stringify(jsonObject)
            console.log(jsonData)
            await this.$tabManager.edge.setConfig(this.configName, jsonData)
            this.selTopicArray = this.getMqttAllTopics()
            return true
        },
        saveEditorJson() {
            this.$emit('handleSaveEditorJson')
        },
        saveJsonFile() {
            this.$emit('handleSaveJsonFile')
        },

        getConfig() {
            this.$emit('handleGetEditorJson')
        },
        mytest() {
            this.saveJsonFile()
        },
        iterateTreeData(data, resultMap) {
            for (const node of data) {
                if (node.children && node.children.length > 0) {
                    for (const child of node.children) {
                        resultMap.set(child.key, child)
                        this.iterateTreeData([child], resultMap) // 递归处理子节点
                    }
                }
            }
        },

        getMqttTopics(keys, publish) {
            const array = new Array()
            if (keys.length === 0) {
                return array
            }
            const parents = this.parseMqttParentMap(this.treeData)
            const dataMap = this.getMqttChildMap()
            keys.forEach(key => {
                if (parents.has(key)) {
                    const values = parents.get(key)
                    if (Array.isArray(values)) {
                        values.forEach(value => {
                            if (dataMap.has(value)) {
                                const data = dataMap.get(value)
                                if (data.publish === publish) {
                                    array.push(data.topic)
                                }
                            }
                        })
                    }
                } else if (dataMap.has(key)) {
                    const data = dataMap.get(key)
                    if (data.publish === publish) {
                        array.push(data.topic)
                    }
                }
            })
            return array
        },

        addValueToMultiMap(key, value, multiMap) {
            if (multiMap.has(key)) {
                multiMap.get(key).push(value)
            } else {
                multiMap.set(key, [value])
            }
        }, 

        addValues(keys, treeData, multiMap) {
            if (keys === undefined) {
                return
            }
            const childKeys = this.parseMqttChildToParentKeyMap(this.treeData)
            const dataMap = this.getMqttChildMap()      
            const parents = this.parseMqttParentMap(treeData)
            keys.forEach(key => {
                if (parents.has(key)) {
                    const values = parents.get(key)
                    if (Array.isArray(values)) {
                        values.forEach(value => {
                            if (dataMap.has(value)) {
                                const data = dataMap.get(value)
                                const parentKey = childKeys.get(data.key)
                                this.addValueToMultiMap(parentKey, data, multiMap)
                            }
                        })
                    }
                } else if (dataMap.has(key)) {
                    const data = dataMap.get(key)
                    if (childKeys.has(key)) {
                        const parentKey = childKeys.get(key)
                        this.addValueToMultiMap(parentKey, data, multiMap)
                    }
                }
            })
        },
        getMqttAllTopics() {
            if (this.publishTopic === undefined && this.subscribeTopic === undefined) {
                return new Array()
            }

            const multiMapSub = new Map()
            const multiMapPub = new Map()
            const jsonMap = new Map()

            const array = new Array()

            this.addValues(this.subscribeTopic, this.treeDataSub, multiMapSub)
            this.addValues(this.publishTopic, this.treeDataPub, multiMapPub)
            // 解析全部数据
            for (const [key, values] of multiMapPub.entries()) {
                const pubTopic = new Array()
                const subTopic = new Array()
                for (const value of values) {
                    if (value.publish) {
                        pubTopic.push(value.topic)
                        continue
                    }
                }
                let jsonObject = {}
                jsonObject['pubTopic'] = pubTopic
                jsonObject['subTopic'] = subTopic
                jsonObject['mqtt'] = key        
                jsonMap.set(key, jsonObject)
            }

            for (const [key, values] of multiMapSub.entries()) {
                const subTopic = new Array()
                const pubTopic = new Array()

                for (const value of values) {
                    if (value.publish) {
                        continue
                    }
                    subTopic.push(value.topic)
                }

                if (jsonMap.has(key)) {
                    const object = jsonMap.get(key)
                    object.subTopic = subTopic
                    jsonMap.set(key, object)
                } else {
                    let jsonObject = {}
                    jsonObject['pubTopic'] = pubTopic
                    jsonObject['subTopic'] = subTopic
                    jsonObject['mqtt'] = key
                    jsonMap.set(key, jsonObject)
                }     
            }    
      
            jsonMap.forEach(element => {
                array.push(element)
            })

            return array
        },

        getMqttChildMap() {
            const resultMap = new Map()
            this.iterateTreeData(this.treeData, resultMap)
            return resultMap
        },

        parseMqttParentMap(data) {
            const resultMap = new Map()
            function processNode(node, parentKey) {
                const nodeKey = node.key
                if (parentKey) {
                    // 如果有父节点，将当前节点的key添加到父节点的数组中
                    const parentArray = resultMap.get(parentKey) || []
                    parentArray.push(nodeKey)
                    resultMap.set(parentKey, parentArray)
                }
                if (node.children && node.children.length > 0) {
                    // 递归处理子节点
                    for (const childNode of node.children) {
                        processNode(childNode, nodeKey)
                    }
                }
            }
            for (const node of data) {
                processNode(node, null) // 初始调用，父节点为空
            }
            return resultMap
        },

        parseMqttChildToParentKeyMap(data) {
            const keyTitleMap = new Map()

            function traverse(node) {
                if (node.children && node.children.length > 0) {
                    node.children.forEach(child => {
                        keyTitleMap.set(child.key, node.title)
                        traverse(child)
                    })
                }
            }

            data.forEach(item => {
                traverse(item)
            })

            return keyTitleMap
        }
    }
}
</script>
  
<style scoped lang="scss">
.ant-form-item {
    margin-bottom: 0;
}
</style>